package com.xz;

import com.xz.printer.BinaryTreeInfo;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author XZ
 * @create 2021-06-06 19:55
 */


//BinaryTreeInfo是工具接口
public class BinarySearchTree<E> implements BinaryTreeInfo {
    //这里比较方法不要写死，即BinarySearchTree<E extends Comparable>

    private int size;
    private Node<E> root;
    private Comparator<E> comparator;

    public BinarySearchTree() {
        this(null);
    }

    public BinarySearchTree(Comparator<E> comparator) {
        this.comparator = comparator;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void clear() {
        root = null;
        size = 0;
    }

    public void add(E element) {
        elementNotNullCheck(element);
        //添加第一个节点
        if (root == null) {
            root = new Node<>(element, null);
            size++;
            return;
        }


        //添加的不是第一个节点
        //找到父节点
        Node<E> parent = root;
        Node<E> node = root;
        int cmp = 0;
        while (node != null) {
            cmp = compare(element, node.element);
            parent = node;
            if (cmp > 0) {
                node = node.right;
            } else if (cmp < 0) {
                node = node.left;
            } else {//相等
                node.element = element;
                return;
            }
        }

        //看看插入到父节点的哪个位置
        Node<E> newNode = new Node<>(element, parent);
        if (cmp > 0) {
            parent.right = newNode;
        } else {
            parent.left = newNode;
        }
        size++;
    }

    public void remove(E element) {//使用者只会传入节点的数据而非节点
        remove(node(element));
    }


    public boolean contains(E element) {
        return node(element)!=null;
    }

    private void remove(Node<E> node) {
        if (node==null) return;
        size--;
        if (node.hasTowChildren()) {//度为2的节点
            //找到后继节点
            Node<E> s = successor(node);
            //用后继节点的值覆盖node的值
            node.element = s.element;
            //删除后继节点
            node = s;//这一步很关键啊！！后面删除的node就是这里的s节点
        }
        //删除node节点（node的度必为0或者1）
        Node<E> replacement = node.left !=null? node.left:node.right;
        if (replacement != null) {//node是度为1的节点
            //更改parent
            replacement.parent = node.parent;
            //更改parent的left、right的指向
            if (node.parent == null) {//node的度是1且为根节点
                root = replacement;
            }else if (node == node.parent.left) {//判断node是父节点但左节点还是右节点。
                node.parent.left=replacement;
            }else if (node == node.parent.right){
                node.parent.right=replacement;
            }
        } else if (node.parent == null) {//node是叶子节点并且是根节点
            root = null;
        } else {//node是叶子节点但不是根节点
            if (node == node.parent.right) {//判断node是父节点但左节点还是右节点。
                node.parent.right=null;
            }else  {
                node.parent.left=null;
            }
        }
    }

    private Node<E> node(E element) {
        Node<E> node = root;
        while (node != null) {
            int cmp = compare(element, node.element);
            if (cmp == 0) return node;
            if (cmp > 0) {
                node = node.right;
            } else {
                node = node.left;
            }
        }
        return null;
    }

    //前序遍历，用递归来写。
    public void perOrderTraversal() {
        perOrderTraversal(root);
    }

    private void perOrderTraversal(Node<E> node) {
        if (node == null) return;
        System.out.println(node.element);
        perOrderTraversal(node.left);
        perOrderTraversal(node.right);
    }

//    //中序遍历
//    public void inorderTraversal() {
//        inorderTraversal(root);
//    }
//
//    public void inorderTraversal(Node<E> node) {
//        if (node == null) return;
//        inorderTraversal(node.left);
//        System.out.println(node.element);
//        inorderTraversal(node.right);
//    }
//
//    //后序遍历
//    public void postorderTraversal() {
//        inorderTraversal(root);
//    }
//
//    public void postorderTraversal(Node<E> node) {
//        if (node == null) return;
//        inorderTraversal(node.left);//先访问左边
//        inorderTraversal(node.right);//再访问右边
//        System.out.println(node.element);//最后访问自己
//    }

//    //层序遍历--需要默写出来
//    public void levelOrderTraversal() {
//        if (root == null) return;
//        Queue<Node<E>> queue = new LinkedList();
//        queue.offer(root);//入队
//        while (!queue.isEmpty()) {
//            Node<E> node = queue.poll();//将每次出队的节点设置为头节点，这里设置的头节点非常关键，是每次递进的起点。
//            System.out.println(node.element);
//            if (node.left != null) {
//                queue.offer(node.left);
//            }
//            if (node.right != null) {
//                queue.offer(node.right);
//            }
//        }
//    }

    public void preorder(Visitor<E> visitor) {
        if (visitor != null) return;
        preorder(root, visitor);
    }

    private void preorder(Node<E> node, Visitor<E> visitor) {
        if (node == null) return;
        if (visitor.stop == true) return;
        visitor.stop = visitor.visit((node.element));
        preorder(node.left, visitor);
        preorder(node.right, visitor);
    }


    public void inorder(Visitor<E> visitor) {
        if (visitor != null) return;
        inorder(root, visitor);
    }


    private void inorder(Node<E> node, Visitor<E> visitor) {
        if (node == null) return;
        inorder(node.left, visitor);
        if (visitor.stop == true) return;
        visitor.stop = visitor.visit((node.element));
        inorder(node.right, visitor);
    }


    public void postorder(Visitor<E> visitor) {
        if (visitor != null) return;
        postorder(root, visitor);
    }

    private void postorder(Node<E> node, Visitor<E> visitor) {
        if (node == null) return;
        postorder(node.left, visitor);
        postorder(node.right, visitor);
        if (visitor.stop == true) return;
        visitor.stop = visitor.visit((node.element));
    }


    public void levelOrder(Visitor<E> visitor) {
        if (root == null || visitor == null) return;
        Queue<Node<E>> queue = new LinkedList();
        queue.offer(root);//入队
        while (!queue.isEmpty()) {
            Node<E> node = queue.poll();//头节点出队
            if (visitor.visit(node.element)) return;
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
    }

    //判断该树是否为完全二叉树
    public boolean isComplete() {
        if (root==null) return false;

        Queue<Node<E>> queue = new LinkedList();
        queue.offer(root);//入队

        boolean leaf = false;

        while (!queue.isEmpty()) {
            Node<E> node = queue.poll();//头节点出队

            if (leaf && !node.isLeaf()) {//这一步很重要
                return false;
            }

            if (node.left != null) {
                queue.offer(node.left);
            } else if (node.right != null) {
                //node.right != null && node.left != null
                return false;
            }

            if (node.right != null) {
                queue.offer(node.right);
            } else {
                //node.right == null && node.left == null
                //node.right != null && node.left == null
                leaf=true;
            }
        }
        return true;
    }

    //计算二叉树的高度，用递归来写。
    public int height1() {
        return height(root);
    }

    public int height(Node<E> node) {
        if (node == null) return 0;
        return 1 + Math.max(height(node.left), height(node.right));
    }

    //计算二叉树的高度，用层序遍历
    public int height2() {
        if (root == null) return 0;
        //树的高度
        int hight = 0;
        //储存着每一层元素的数量
        int levelSize = 1;
        Queue<Node<E>> queue = new LinkedList();
        queue.offer(root);

        while (!queue.isEmpty()) {
            Node<E> node = queue.poll();
            levelSize--;

            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
            if (levelSize == 0) {//意味着即将访问下一层
                levelSize= queue.size();
                hight++;
            }
        }
        return hight;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        toString(root, sb, "");
        return sb.toString();
    }

    public void toString(Node<E> node, StringBuilder sb, String prefix) {
        if (node == null) return;
        sb.append(prefix).append(node.element).append("\n");
        toString(node.left, sb, prefix + "L---");
        toString(node.right, sb, prefix + "R---");
    }

    /**
     * @param e1
     * @param e2
     * @return 返回值等于零，代表e1和e2相等。返回值大于零，代表代表e1大于e2；返回值小于零，代表代表e1小于e2；
     * 利用构造器使得默认的比较方式是Comparable
     */
    private int compare(E e1, E e2) {
        if (comparator != null) {
            return comparator.compare(e1, e2);
        }
        return ((Comparable<E>) e1).compareTo(e2);
    }

    private void elementNotNullCheck(E element) {
        if (element == null) {
            throw new IllegalArgumentException("element must not be null");
        }
    }

    /**
     * 前驱节点
     * @param node
     * @return
     */
    private Node<E> predecessor(Node<E> node) {
        if (node==null) return null;
        //前驱节点在左子树当中，left.right.right.right.right
        Node<E> p = node.left;
        if (p != null) {
            while (p.right != null) {
                p=p.right;
            }
            return p;
        }
        //从父节点、祖父节点中寻找前驱节点。
        while (node.parent != null && node.parent.left==node) {
            node = node.parent;
        }
        //node.parent==null
        //node = node.parent.right
        return node.parent;
    }

    /**
     * 后继节点
     * @param node
     * @return
     */
    private Node<E> successor(Node<E> node) {
        if (node==null) return null;
        //前驱节点在左子树当中，right.right.right.right.right
        Node<E> p = node.right;
        if (p != null) {
            while (p.left != null) {
                p=p.left;
            }
            return p;
        }
        //从父节点、祖父节点中寻找前驱节点。
        while (node.parent != null && node.parent.right==node) {
            node = node.parent;
        }
        return node.parent;
    }


    public static abstract class Visitor<E> {
        boolean stop;

        /**
         * @param element
         * @return：如果返回true则代表停止遍历
         */
        abstract boolean visit(E element);
    }

    private static class Node<E> {
        E element;
        Node<E> left;
        Node<E> right;
        Node<E> parent;

        public Node(E element, Node<E> parent) {
            this.element = element;
            this.parent = parent;
        }

        public boolean isLeaf() {
            return left == null && right == null;
        }

        public boolean hasTowChildren() {
            return left!= null && right != null;
        }
    }

    //print工具方法
    @Override
    public Object root() {
        return root;
    }

    @Override
    public Object left(Object node) {
        return ((Node<E>) node).left;
    }

    @Override
    public Object right(Object node) {
        return ((Node<E>) node).right;
    }

    @Override
    public Object string(Object node) {
        Node<E> myNode = (Node<E>) node;
//        String parentString = "null";
//        if (myNode.parent != null) {
//            parentString = myNode.parent.element.toString();
//        }
//        return myNode.element + "_" + parentString;
        return myNode.element.toString();
    }
}
